<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-center-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="http://7xqdz8.com1.z0.glb.clouddn.com/avatar.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="http://7xqdz8.com1.z0.glb.clouddn.com/avatar.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="笔记,算法," />










<meta name="description" content="0. 快速排序由Tony Hoare在1962年发明，这是一个分治算法，它就在原地完成排序，类似与插入排序。优点：节约内存资源，非常实用，线性复杂度">
<meta property="og:type" content="article">
<meta property="og:title" content="分治法之快排&随机化">
<meta property="og:url" content="/2016/07/18/divide-conquer/index.html">
<meta property="og:site_name" content="一路前行">
<meta property="og:description" content="0. 快速排序由Tony Hoare在1962年发明，这是一个分治算法，它就在原地完成排序，类似与插入排序。优点：节约内存资源，非常实用，线性复杂度">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718array.png">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718array1.png">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort0.png">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort1_0.png">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort1_1.png">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort3_1.png">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort4_1.png">
<meta property="og:image" content="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort5.png">
<meta property="og:updated_time" content="2016-07-18T13:20:56.768Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分治法之快排&随机化">
<meta name="twitter:description" content="0. 快速排序由Tony Hoare在1962年发明，这是一个分治算法，它就在原地完成排序，类似与插入排序。优点：节约内存资源，非常实用，线性复杂度">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="/2016/07/18/divide-conquer/"/>





  <title>分治法之快排&随机化 | 一路前行</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8193f7e44c62cdda245d5f109196c830";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">一路前行</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Always believe that some thing wonderful is about to happen.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="/2016/07/18/divide-conquer/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Voyager">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://7xqdz8.com1.z0.glb.clouddn.com/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一路前行">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">分治法之快排&随机化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-07-18T21:00:00+08:00">
                2016-07-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/算法与数据结构/" itemprop="url" rel="index">
                    <span itemprop="name">算法与数据结构</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="0-__u5FEB_u901F_u6392_u5E8F"><a href="#0-__u5FEB_u901F_u6392_u5E8F" class="headerlink" title="0. 快速排序"></a>0. 快速排序</h1><p>由Tony Hoare在1962年发明，这是一个分治算法，它就在原地完成排序，类似与插入排序。<br>优点：节约内存资源，非常实用，线性复杂度</p>
<a id="more"></a>
<h1 id="1-__u5206_u6CBB_u7B56_u7565"><a href="#1-__u5206_u6CBB_u7B56_u7565" class="headerlink" title="1. 分治策略"></a>1. 分治策略</h1><h2 id="1-1__u5206"><a href="#1-1__u5206" class="headerlink" title="1.1 分"></a>1.1 分</h2><p>快速排序通过选取一个关键数据，再根据它的大小，把原数组分为两个子数组，第一个数组里面的元数据都比第二个数组里的元素大或者相等。<br><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718array.png" alt="数组"></p>
<h2 id="1-2__u6CBB"><a href="#1-2__u6CBB" class="headerlink" title="1.2 治"></a>1.2 治</h2><p>对两个子数组进行递归排序。</p>
<h2 id="1-3__u5408"><a href="#1-3__u5408" class="headerlink" title="1.3 合"></a>1.3 合</h2><p>最后得到的数组便是排好序的数组。</p>
<blockquote>
<p>快速排序关键的一步就是 <code>分</code> ，即递归地划分数组，而归并排序就可以说是递归地合并数组。</p>
</blockquote>
<h1 id="2-__u5206_u6790"><a href="#2-__u5206_u6790" class="headerlink" title="2. 分析"></a>2. 分析</h1><p>伪代码如下所示:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/* &#21010;&#20998; */&#10;Partition(A, p, q)  // A[p...q]&#10;x &#60;- A[p]           // &#38656;&#35201;&#20316;&#27604;&#36739;&#30340;&#25968;&#65292;&#21736;&#20853;&#10;i &#60;- p&#10;for j &#60;- p+1 to q&#10;    do if A[j] &#60;= x&#10;        then i &#60;- i+1&#10;           exch A[i] &#60;-&#62; A[j]&#10;exch A[p] &#60;-&#62; A[i]&#10;return i&#10;&#10;/* &#24555;&#36895;&#25490;&#24207; */&#10;QuitSort(A, p, q)&#10;if(p&#60;q)&#10;    then r &#60;- Partition(A, p, q)&#10;        QuickSort(A, p, r)&#10;        QuickSort(A, r, q)&#10;        &#10;        &#10;/* &#21021;&#22987;&#35843;&#29992; */&#10;Init call:&#10;QuickSort(A, 1, n)</span><br></pre></td></tr></table></figure></p>
<h2 id="2-1__u601D_u8DEF"><a href="#2-1__u601D_u8DEF" class="headerlink" title="2.1 思路"></a>2.1 思路</h2><p><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718array1.png" alt="思路"><br>以j为循环变量，从p+1开始遍历，对于每一个元素，都与x进行比较：</p>
<ul>
<li>若大于等于x，则不管，直接继续</li>
<li>若小于x，i的位置向前移动一位，这时候再将i位置的值与j位置的值进行交换<br>循环结束后，将哨兵的值放回到i循环结束后的位置上</li>
</ul>
<h2 id="2-2__u6548_u7387_u5206_u6790"><a href="#2-2__u6548_u7387_u5206_u6790" class="headerlink" title="2.2 效率分析"></a>2.2 效率分析</h2><ul>
<li>最坏情况: 已经排好序或者排成逆序，此时不如插入排序算法<br>T(n) = Θ(n^2)</li>
<li>最优情况: 划分正好处在正中央<br>T(n) = Θ(n lgn)<blockquote>
<p>当划分为1:9时，经验证同为最优情况</p>
</blockquote>
</li>
</ul>
<h1 id="3-__u793A_u4F8B"><a href="#3-__u793A_u4F8B" class="headerlink" title="3. 示例"></a>3. 示例</h1><blockquote>
<p>对 6、10、13、5、8、3、2、11 进行快速排序划分:</p>
</blockquote>
<ul>
<li><p>第一步，i指向6，j指向10，哨兵赋值为6<br><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort0.png" alt="赋值"></p>
</li>
<li><p>第二步，j向前移动，寻找比哨兵值6小的元素<br><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort1_0.png" alt="移动"></p>
</li>
<li><p>第三步，交换i+1与j值<br><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort1_1.png" alt="交换"></p>
</li>
<li><p>重复第二步、第三步<br><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort3_1.png" alt="重复步骤"><br><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort4_1.png" alt="重复步骤"></p>
</li>
<li><p>最后一步，交换哨兵与i所在位置<br><img src="http://7xqdz8.com1.z0.glb.clouddn.com/160718sort5.png" alt="交换哨兵"></p>
</li>
</ul>
<hr>
<h1 id="4-__u968F_u673A_u5316_u5FEB_u6392"><a href="#4-__u968F_u673A_u5316_u5FEB_u6392" class="headerlink" title="4. 随机化快排"></a>4. 随机化快排</h1><p>简单说就是在排序前将数据进行随机化，它具有一下优点:</p>
<ul>
<li>运行时间不依赖于输入的序列顺序</li>
<li>无需对输入序列的分布做出任何假设</li>
<li>没有一种特定的输入引起最差的情况</li>
<li>最差的情况由随机数生成器产生</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://7xqdz8.com1.z0.glb.clouddn.com/pay_weixin.png" alt="Voyager 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://7xqdz8.com1.z0.glb.clouddn.com/pay_alipay.jpg" alt="Voyager 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/笔记/" rel="tag"># 笔记</a>
          
            <a href="/tags/算法/" rel="tag"># 算法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/05/26/customView/" rel="next" title="浅谈自定义View">
                <i class="fa fa-chevron-left"></i> 浅谈自定义View
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/07/22/EventBus/" rel="prev" title="EventBus 源码分析">
                EventBus 源码分析 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://7xqdz8.com1.z0.glb.clouddn.com/avatar.png"
                alt="Voyager" />
            
              <p class="site-author-name" itemprop="name">Voyager</p>
              <p class="site-description motion-element" itemprop="description">Android Developer</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">41</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/a-voyager" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:w19961009@126.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/u/2306071720" target="_blank" title="微博">
                    
                      <i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#0-__u5FEB_u901F_u6392_u5E8F"><span class="nav-number">1.</span> <span class="nav-text">0. 快速排序</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#1-__u5206_u6CBB_u7B56_u7565"><span class="nav-number">2.</span> <span class="nav-text">1. 分治策略</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1__u5206"><span class="nav-number">2.1.</span> <span class="nav-text">1.1 分</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2__u6CBB"><span class="nav-number">2.2.</span> <span class="nav-text">1.2 治</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3__u5408"><span class="nav-number">2.3.</span> <span class="nav-text">1.3 合</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-__u5206_u6790"><span class="nav-number">3.</span> <span class="nav-text">2. 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1__u601D_u8DEF"><span class="nav-number">3.1.</span> <span class="nav-text">2.1 思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2__u6548_u7387_u5206_u6790"><span class="nav-number">3.2.</span> <span class="nav-text">2.2 效率分析</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-__u793A_u4F8B"><span class="nav-number">4.</span> <span class="nav-text">3. 示例</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-__u968F_u673A_u5316_u5FEB_u6392"><span class="nav-number">5.</span> <span class="nav-text">4. 随机化快排</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">WuHaojie</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  








  





  

  

  

  

  

  

</body>
</html>
